window.addEventListener('load', () => {
  const container = document.querySelector('.scroll-container')

  const imgs = ['../../public/img/1.jpg', '../../public/img/2.jpg', '../../public/img/3.jpg']

  let curIndex = 0
  let isAnimating = false
  function createElement(index, className) {
    const div = document.createElement('div')
    div.className = `item ${className}`

    const img = document.createElement('img')
    img.src = imgs[index]

    div.appendChild(img)
    return div
  }
  function resetElements() {
    container.innerHTML = ''
    const prevIndex = (curIndex - 1 + imgs.length) % imgs.length
    const nextIndex = (curIndex + 1) % imgs.length

    container.appendChild(createElement(prevIndex, 'prev'))
    container.appendChild(createElement(curIndex, 'cur'))
    container.appendChild(createElement(nextIndex, 'next'))
  }
  window.addEventListener('wheel', e => {
    if (isAnimating) return
    if (e.deltaY > 0) {
      isAnimating = true
      container.classList.add('scroll-down')
    } else if (e.deltaY < 0) {
      isAnimating = true
      container.classList.add('scroll-up')
    }
  })
  container.addEventListener('transitionend', () => {
    if (!isAnimating) return
    if (container.classList.contains('scroll-down')) {
      curIndex = (curIndex + 1) % imgs.length
    } else if (container.classList.contains('scroll-up')) {
      curIndex = (curIndex - 1 + imgs.length) % imgs.length
    }
    resetElements()
    container.className = 'scroll-container'
    isAnimating = false
  })
  resetElements()
})
